// templates/deliver/pages/location/location.js
import Notify from '@vant/weapp/notify/notify'
import Dialog from '@vant/weapp/dialog/dialog'
import { clearUserLocalStorage, userRequest } from '../../../../utils/util'
import { authorization } from '../../../../utils/location'
const app = getApp()

Page({
  /**
   * 页面的初始数据
   */
  data: {
    // 存储订单列表
    orders: [],
    // 存储地图标记，用于子订单相关显示
    markers: [],
    main_order_ids: [], //合并后数量
    // 是否全选的状态
    select_all_status: false,
    // 计数变量
    count: 0,
    // 存储获取到的区域信息
    area: '',
    // 地图的缩放级别
    scale: 12.1,
    // 当前位置的纬度
    latitude: 0,
    // 当前位置的经度
    longitude: 0,
    // 选中的配送员索引
    selected_delivery_man_index: 0,
    // 选中的配送员 ID
    dispatch_delivery_man_id: 0,
    // 布尔值状态
    checked: true,
    // 级别
    level: 0,
    // 图片路径
    image: '/templates/deliver/img/business.png',
    selected_ids: [],
    showCal: false,
    current_delivery_man_id: '',
    current_delivery_district_id: '',
    access_token: null,
    show_popup: false,
    searchOrder: [],
    page: 1, // 页码
    size: 50, // 条数
    totalPages: 0, // 总页数
    isLoading: false, // 加载状态锁
    delivery_district_list: '',
    delivery_man_list: ''
  },
  /**
   * 生命周期函数 -- 监听页面加载
   */
  async onLoad(options) {
    const { delivery_status } = options
    const now = Date.now() / 1000
    const expirationTime = app.session.expiration_time || 0
    if (now > expirationTime) {
      console.log('已过登录有效期!')
      app.session = {}
      clearUserLocalStorage()
      wx.reLaunch({
        url: '/pages/selectID/selectID'
      })
    }
    let current_delivery_man_id = wx.getStorageSync('current_delivery_man_id') || 0
    let current_delivery_district_id = wx.getStorageSync('current_delivery_district_id') || 0
    // 从 app 会话中获取配送员级别
    let level = wx.getStorageSync('level')
    let access_token = wx.getStorageSync('access_token')
    let delivery_man_list = app.session.delivery_man_list
    let delivery_district_list = app.session.delivery_district_list
    console.log(current_delivery_man_id)
    console.log(current_delivery_district_id)
    // 更新页面数据
    this.setData({
      current_delivery_man_id,
      access_token,
      current_delivery_district_id,
      level,
      delivery_status,
      delivery_district_list,
      delivery_man_list
    })
    this.get_waiting_delivery()
  },
  // 查询订单信息
  queryOrder(e) {
    console.log(e)
    const orderNo = e.currentTarget.dataset.index
    console.log(orderNo)
    this.getViewOrderInfo(orderNo)
  },

  // 获取订单详细信息
  async getViewOrderInfo(orderNo) {
    const { access_token } = this.data
    const header = {
      'Content-Type': 'application/json',
      'x-api-key': access_token
    }
    const data = {
      order_no: orderNo
    }
    const url = app.globalData.API + '/delivery/index/query-order-info'
    try {
      const res = await userRequest(url, 'POST', data, header)
      if (res.code === 200) {
        const orderInfo = JSON.stringify(res.data)
        console.log('orderInfo:', orderInfo)
        wx.navigateTo({
          url: '/templates/deliver/pages/orderInfo/orderInfo',
          success: res => {
            res.eventChannel.emit('orderInfo', orderInfo)
          }
        })
      } else {
        wx.showToast({
          title: res.message,
          icon: 'error',
          duration: 2000
        })
      }
    } catch (error) {
      if (error.code === 0) {
        clearUserLocalStorage()
        wx.reLaunch({
          url: '/pages/selectID/selectID'
        })
      }
    }
  },

  /**
   * 获取待发货订单数据
   */
  async get_waiting_delivery() {
    // const that = this;
    // this.setData(Object.assign({}, this.data, {
    //   orders: [],
    //   main_order_ids: [],
    //   markers: [],
    //   selected_ids: []
    // }));
    // 仅在页码为 1 时清空数据
    if (page === 1) {
      this.setData(Object.assign({}, this.data, {
        orders: [],
        main_order_ids: [],
        markers: [],
        selected_ids: []
      }));
    }
    const { access_token, current_delivery_man_id, current_delivery_district_id, page, size } =
      this.data
    const header = {
      'Content-Type': 'application/json',
      'x-api-key': access_token
    }
    const data = {
      current_delivery_district_id,
      current_delivery_man_id,
      page,
      size
    }
    const url = app.globalData.API + '/delivery/index/waiting-delivery';

    // let url, requestData;
    // 从页面数据中获取当前配送员 ID 和当前配送区域 ID

    // 获取当前位置
    await this.get_current_location()
    const res = await userRequest(url, 'POST', data, header)


    if (res.code === 200) {
      const newOrders = res.data.orders
      const maxDistance = res.data.max_distance
      const total = res.data.pagination.total_pages
      // const markers = []
      const newMarkers = []
      for (let i = 0; i < newOrders.length; i++) {
        const longitude = newOrders[i].longitude // 经度
        const latitude = newOrders[i].latitude // 纬度
        newOrders[i].latitude = latitude
        newOrders[i].longitude = longitude
        newOrders[i].delivery_merge_id = parseInt(newOrders[i].delivery_merge_id)
        newOrders[i].distance = this.getDistance(
          latitude,
          longitude,
          this.data.latitude,
          this.data.longitude
        )
      }
      newOrders.sort((a, b) => a.distance - b.distance)
      const mainOrderIds = []
      for (let i = 0; i < newOrders.length; i++) {
        if (newOrders[i].delivery_merge_id === 0) {
          mainOrderIds.push(newOrders[i].order_id)
          newMarkers.push({
            iconPath: '../../img/icon-hc.png',
            id: 900000000 + parseInt(newOrders[i].order_id),
            order_id: newOrders[i].order_id,
            select_id: `#card-${newOrders[i].order_id}`,
            latitude: newOrders[i].latitude,
            longitude: newOrders[i].longitude,
            width: 23,
            height: 23,
            nearbyCount: 0,
            nearMarkers: [],
            nearMarkersInfo: [],
            callout: {
              content: `${newOrders[i].contact} ${i + 1}`,
              store_name: newOrders[i].contact,
              fontSize: 14,
              padding: true,
              color: '#444',
              display: 'ALWAYS',
              textAlign: 'center',
              borderRadius: 5,
              bgColor: '#ffffff'
            }
          })
        }
      }
      // 计算每两个定位点之间的距离
      for (let i = 0; i < newMarkers.length; i++) {
        for (let j = i + 1; j < newMarkers.length; j++) {
          const distance = this.calculateDistance(
            newMarkers[i].latitude,
            newMarkers[i].longitude,
            newMarkers[j].latitude,
            newMarkers[j].longitude
          )
          if (distance <= maxDistance) {
            newMarkers[i].nearbyCount += 1
            newMarkers[j].nearbyCount += 1
            newMarkers[i].nearMarkers.push(newMarkers[j].id)
            newMarkers[j].nearMarkers.push(newMarkers[i].id)
            newMarkers[i].nearMarkersInfo.push({ distance: maxDistance - distance })
          }
        }
      }
      newMarkers.forEach(marker => {
        marker.callout.content += ` (${marker.nearbyCount})`
      })

      this.setData({
        markers: [...newMarkers, ...this.data.markers], //地图显示的标记点
        orders: [...this.data.orders, ...newOrders], //总订单数
        selected_ids: [], //选中的订单
        main_order_ids: [...this.data.main_order_ids, ...mainOrderIds], //主订单
        total //总页数
      })
      Notify({
        type: 'success',
        message: '数据加载完成'
      })
    }
  },
  // 处理选择订单事件
  onCheck(e) {
    const selectedIds = e.detail
    const mainOrderIds = this.data.main_order_ids
    console.log('selected_ids:', selectedIds)
    let selectAllStatus = false
    if (selectedIds.length === mainOrderIds.length) {
      selectAllStatus = true
    }
    this.setData({
      selected_ids: selectedIds,
      select_all_status: selectAllStatus
    })
  },

  // 已送达 处理配送人员下拉框改变事件
  on_delivery_dropdown_change(e) {
    const current_delivery_man_id = e.detail
    this.setData({
      current_delivery_man_id: current_delivery_man_id,
      orders: [],
      markers: [],
      main_order_ids: [],
    })
    wx.setStorageSync('current_delivery_man_id', current_delivery_man_id)
    this.get_waiting_delivery()
  },
  /**
   * 处理订单选中状态变化
   */
  /**
   * 处理地图标记点击事件
   */
  onTapMarker(e) {
    const markerId = parseInt(e.detail.markerId)
    const markers = this.data.markers
    console.log(e)
    console.log(markerId, markers)
    const marker = markers.find(m => m.id === markerId) // 根据地图标记的 id 找到对应的 marker
    console.log(marker)
    if (marker) {
      const query = wx.createSelectorQuery()
      query.select(marker.select_id).boundingClientRect() // 根据订单 id 找到对应的卡片
      query.exec(function (res) {
        console.log('res', res)
        const cardRect = res[0]
        if (cardRect) {
          wx.pageScrollTo({
            scrollTop: cardRect.top
          })
        }
      })
    }
  },

  /**
   * 处理配送区域下拉框选择变化
   */
  on_delivery_district_dropdown_change(e) {
    const current_delivery_district_id = e.detail
    this.setData({
      current_delivery_district_id: current_delivery_district_id,
      orders: [],
      markers: [],
      main_order_ids: [],
    })
    wx.setStorageSync('current_delivery_district_id', current_delivery_district_id)
    this.get_waiting_delivery()
  },

  /**
   * 获取当前位置
   */
  async get_current_location() {
    let res = await authorization()
    console.log("authorization res", res);
    this.setData({
      longitude: res.longitude,
      latitude: res.latitude
    })
  },

  /**
   * 生命周期函数 -- 监听页面初次渲染完成
   */
  onReady() {
    // 可在此添加页面初次渲染完成后的逻辑
  },

  /**
   * 生命周期函数 -- 监听页面显示
   */
  onShow() {
    // 可在此添加页面显示时的逻辑
  },

  /**
   * 生命周期函数 -- 监听页面隐藏
   */
  onHide() {
    // 可在此添加页面隐藏时的逻辑
  },

  /**
   * 生命周期函数 -- 监听页面卸载
   */
  onUnload() {
    // 可在此添加页面卸载时的逻辑
  },
  onSearchChange(e) {
    let search_mobile = e.detail.replace(/\s+/g, '')
    // 验证手机号格式
    let mobilePattern = /^1[3-9]\d{9}$/

    if (!search_mobile) {
      this.setData({
        orders: this.data.searchOrder
      })
      this.data.searchOrder = [] // 清空备份
    } else {
      if (!mobilePattern.test(search_mobile)) {
        Toast.fail('请输入正确的手机号')
        return
      }
      if (this.data.searchOrder.length === 0) {
        // 首次搜索时备份原始数据
        this.data.searchOrder = [...this.data.orders]
      }
      // const allOrders = this.data.orders;
      const filteredOrders = this.data.orders.filter(order => {
        // 假设订单中有 mobile 和 contact 字段分别表示手机号和用户名
        return order.mobile.includes(search_mobile)
      })
      this.setData({
        orders: filteredOrders
      })
    }
  },
  onClearChange(e) {
    if (this.data.searchOrder.length > 0) {
      // 恢复备份数据
      this.setData({
        orders: this.data.searchOrder
      })
      this.data.searchOrder = [] // 清空备份
    }
  },
  calculateDistance(lat1, lon1, lat2, lon2) {
    const toRad = x => (x * Math.PI) / 180
    const R = 6371 // 地球半径（公里）
    const dLat = toRad(lat2 - lat1)
    const dLon = toRad(lon2 - lon1)
    const a =
      Math.sin(dLat / 2) * Math.sin(dLat / 2) +
      Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) * Math.sin(dLon / 2) * Math.sin(dLon / 2)
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
    const distance = R * c
    return distance * 1000 // 转换为米
  },
  /**
   * 根据距离计算远近排序订单
   */
  //   sort_orders(orders) {
  //     let arr = [...orders]
  //     let s = ''
  //     for (var i = 1; i < arr.length; i++) {
  //       for (var j = i; j > 0; j--) {
  //         if (arr[j].distance > arr[j - 1].distance) {
  //           s = arr[j]
  //           arr[j] = arr[j - 1]
  //           arr[j - 1] = s
  //         }
  //       }
  //     }
  //     return arr.reverse()
  //   },

  /**
   * 经纬度计算距离
   */
  // ... existing code ...
  //   success: res => {
  //     if (res.data.code === 200) {
  //       Notify({ type: 'success', message: '解绑成功~' })
  //       this.onClose()
  //       this.get_in_delivery()
  //     } else {
  //       Notify({ type: 'warning', message: '解绑失败~' })
  //     }
  //   },
  // ... existing code ...
  getDistance(lat1, lng1, lat2, lng2) {
    var radLat1 = (lat1 * Math.PI) / 180.0
    var radLat2 = (lat2 * Math.PI) / 180.0
    var a = radLat1 - radLat2
    var b = (lng1 * Math.PI) / 180.0 - (lng2 * Math.PI) / 180.0
    var s =
      2 *
      Math.asin(
        Math.sqrt(
          Math.pow(Math.sin(a / 2), 2) +
          Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)
        )
      )
    s = s * 6378.137 // EARTH_RADIUS;
    s = Math.round(s * 10000) / 10000
    s = s.toFixed(2)
    return parseFloat(s)
  },

  /**
   * 页面相关事件处理函数 -- 监听用户下拉动作
   */
  onPullDownRefresh() {
    this.setData({
      page: 1, // 重置页码为 1
      orders: [], // 清空订单数组
      main_order_ids: [], // 清空主订单数组
      markers: [],
    })
    // console.log(this.data.orders)
    this.get_waiting_delivery()
    wx.stopPullDownRefresh()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    // 可在此添加页面上拉触底时的逻辑
    const { page, total } = this.data
    if (page < total) {
      this.setData({
        page: page + 1 // 增加页码
      })
      this.get_waiting_delivery()
    } else {
      Notify({
        type: 'warning',
        message: '没有更多数据了'
      })
      this.setData({
        isLoading: true // 显示指定元素
      })
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    // 可在此添加分享相关逻辑
  },

  /**
   * 点击导航事件
   */
  getLocation(e) {
    console.log(e)
    const that = this
    let index = e.currentTarget.dataset['index'] // 获取传递的参数
    let order = that.data.orders[index]
    console.log(index)
    console.log(order)
    var address = order.address
    var contact = order.contact
    var mobile = order.mobile
    var latitude = order.latitude
    var longitude = order.longitude
    wx.openLocation({
      latitude: Number(latitude), // 要去的纬度 - 地址 一定不要使数字
      longitude: Number(longitude), // 要去的经度 - 地址
      address: address,
      name: contact + '/' + mobile,
      scale: 15
    })
  },

  /**
   * 查看订单商品
   */
  viewOrderGoods(event) {
    let order_no = event.target.dataset.index
    wx.navigateTo({
      url: '/templates/deliver/pages/orderGoods/orderGoods?order_no=' + order_no
    })
  },

  /**
   * 解析 JSON 字符串为数组
   */
  parseJsonOrEmptyArray(jsonString) {
    try {
      const parsed = JSON.parse(jsonString)
      if (Array.isArray(parsed)) {
        // 检查数组元素的结构，并进行转换
        return parsed.map(item => {
          if (typeof item === 'object' && 'url' in item) {
            return item // 已经是 { url: 'https://xxxxx' } 格式
          } else if (typeof item === 'object' && item.url) {
            return item.url // 处理 { url: { url: 'https://xxxxx' } } 格式
          } else {
            return {} // 无效的对象格式，返回空对象
          }
        })
      } else {
        return []
      }
    } catch (e) {
      return []
    }
  },

  /**
   * 去派单事件
   */
  ballPopup(e) {
    console.log(e)
    let that = this
    let index = parseInt(e.currentTarget.dataset.index)
    let current_order_id = e.currentTarget.dataset.order_id // 获取传递的 id 参数
    let current_order = this.data.orders[index]
    console.log(current_order)
    current_order.delivery_photo = that.parseJsonOrEmptyArray(current_order.delivery_photo)
    this.setData({
      show_popup: true,
      current_order_id,
      current_order
    }) // 打开弹窗
  },

  /**
   * 关闭弹窗
   */
  onPopupClose() {
    this.setData({
      show_popup: false
    })
  },

  /**
   * 处理备注输入
   */
  onRemarkInput(e) {
    let that = this
    let value = e.detail
    let current_order = that.data.current_order
    current_order.delivery_remark = value
    this.setData({
      current_order
    })
  },

  /**
   * 派单操作
   */
  dispatch_delivery_order() {
    let that = this
    let current_order = that.data.current_order
    let dispatch_delivery_man_id = that.data.dispatch_delivery_man_id

    console.log(dispatch_delivery_man_id)
    if (dispatch_delivery_man_id === undefined || dispatch_delivery_man_id === 0) {
      Notify({
        type: 'warning',
        message: '请选择配送员'
      })
      return
    }
    console.log(current_order.delivery_remark)
    let order_id = current_order.order_id
    wx.request({
      url: app.globalData.API + '/delivery/index/dispatch-delivery-order',
      header: {
        'Content-Type': 'application/json',
        'x-api-key': this.data.access_token
      },
      method: 'POST',
      data: {
        order_id,
        dispatch_delivery_man_id
      },
      success(res) {
        if (res.data.code === 200) {
          Notify({
            type: 'success',
            message: '派单成功'
          })
          that.onPopupClose()
          that.get_waiting_delivery()
        } else {
          Notify({
            type: 'success',
            message: '派单失败'
          })
          that.onPopupClose()
        }
      }
    })
  },

  /**
   * 处理下拉框选择变化
   */
  on_dropdown_change(e) {
    const dispatch_delivery_man_id = e.detail
    console.log(dispatch_delivery_man_id)

    // 根据 dispatch_delivery_man_id 找出 delivery_man 在 delivery_man_list 的索引值
    const selected_delivery_man_index = this.data.delivery_man_list.findIndex(
      d => d.value === dispatch_delivery_man_id
    )

    this.setData({
      selected_delivery_man_index,
      dispatch_delivery_man_id
    })
  },

  /**
   * 处理派单下拉框选择变化
   */
  on_dispatch_dropdown_change(e) {
    const dispatch_delivery_man_id = e.detail
    const delivery_man = this.data.delivery_man_list.find(d => d.value === dispatch_delivery_man_id)
    if (delivery_man) {
      this.setData({
        dispatch_delivery_man_id
      })
    }
  }
})
